package com.pompom.workers;

import gummy.database.GummyClient;
import nl.ansuz.android.steam.dota.response.match.GetMatchDetailsResponse;

import com.pompom.matchcrawler.MPBuffer;
import com.pompom.matchcrawler.MatchFetcher;
import com.pompom.matchcrawler.MatchPersistor;
import com.pompom.matchcrawler.MultiInstanceManager;
import com.pompom.matchcrawler.ResponseTypeChecker;
import com.pompom.matchcrawler.types.TOMatchSkillInfo;
import com.pompom.matchcrawler.types.TOMatchWorkQueue;

public class MatchDetailWorker extends AbstractWorker{



	protected long currentMatch;
	protected TOMatchWorkQueue[] queue=null;
	protected int queuePos=0;
	protected int fetchSize=10;
	boolean immediate=true;
	MatchPersistor mpersistor = new MatchPersistor();
	public MatchDetailWorker()
	{

	}


	protected void retrieveNextMatchesFromQueue()
	{
		int total=MultiInstanceManager.getTotalMod(this);
		int mynum=MultiInstanceManager.getMyDivisor(this);
		queue = (TOMatchWorkQueue[]) GummyClient.getInstance("QUEUES").executeQueryTO
				("SELECT * FROM MATCH_WORK_QUEUE WHERE MATCHID % "+total+"="+mynum+" AND MATCHID >260000000 ORDER BY PRIORITY ASC, TS ASC, MATCHID DESC LIMIT "+fetchSize, new Object[]{}, TOMatchWorkQueue.class);
		//System.out.println("SELECT * FROM MATCH_WORK_QUEUE WHERE MATCHID % "+total+"="+mynum+" AND MATCHID >260000000 ORDER BY PRIORITY ASC, TS ASC, MATCHID DESC LIMIT "+fetchSize);
		queuePos=0; 
	}

	public void work()
	{


		if (queue==null || queuePos>=queue.length)
		{
			retrieveNextMatchesFromQueue();
		}

		if (queue ==null) return;
		if (queuePos<queue.length)
		{
			currentMatch = queue[queuePos].getMatchid();

			//System.out.println("retrieving match "+currentMatch+" work queue");
			MatchFetcher fetcher = new MatchFetcher(currentMatch);
			GetMatchDetailsResponse match = fetcher.fetch();
			 if (match==null) {
				 queuePos++;
				 try {
					Thread.sleep(600 +(int)( Math.random()*1000f));
				} catch (InterruptedException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				 return;
			 }
			if (fetcher.getResponseError()==ResponseTypeChecker.NO_ERROR)
			{
				int ret = MatchPersistor.isMatchAlreadyInDB(currentMatch);
				if (ret ==1)
				{
					 	//System.out.println("ret 1 "+currentMatch);
				}
				else if (ret == 0)
				{
				System.out.println("persisting match "+currentMatch);
				if (queue[queuePos].getPriority() == TOMatchWorkQueue.PRIORITY_DONTBUFFER)
					mpersistor.persist(match,true);
				else
					mpersistor.persist(match,immediate);
				} 
			}
			else
				System.out.println("Error "+fetcher.getResponseError());
			//System.out.println("done");



			if (clearRequestFromQueue(currentMatch))
			{
				queuePos++;
			}
			sleepPlus=0;
		}
		else 
			{
				if (sleepPlus==0)
					System.out.println("MATCH_WORK_QUEUE Queue is empty!");
				sleepPlus = 1000;
			}
		
		if (isStopWork())
		{
			mpersistor.flushAll();
		}


	}

	public boolean clearRequestFromQueue(long matchID)
	{
		
		GummyClient.getInstance("QUEUES").execute("DELETE FROM MATCH_WORK_QUEUE where MATCHID= ?", new Object[]{""+matchID});
		return true;
	}
	
	
	/**
	 * 
	 * @param matchid
	 * @return true if match is already in queue
	 */
	public static boolean putMatchInWorkQueue(long matchid, byte priority)
	{
	
		
		if (matchid<260000000)
			return true;
	  boolean matchAlreadyInQueue = GummyClient.getInstance("QUEUES").executeQueryBoolean("SELECT 1 FROM MATCH_WORK_QUEUE WHERE MATCHID =?", new Object[]{  (long)matchid});
	 
 
	  if (!matchAlreadyInQueue)
	  {
		TOMatchWorkQueue tomwk = new TOMatchWorkQueue();
		tomwk.setMatchid( matchid);
		tomwk.setPriority(priority);
		tomwk.setTimestamp(System.currentTimeMillis());
		try
		{
		GummyClient.getInstance("QUEUES").executeInsertTO(tomwk);		
		} catch (RuntimeException e){
			
			if (e.getCause().getCause() instanceof com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException)
			{
				System.out.println("duplicate !!! quem diria "+matchid);
			}
			else
				throw e;
		}
		
	  }
	  else
		  {
		 
		  
		  return true;
		  }
	  return false;
	}


	@Override
	public void setParameters() { 

		 if (getParameter("fetchSize")!=null)
		 {
			 fetchSize = Integer.parseInt(getParameter("fetchSize"));
		 }
		 
		 if (getParameter("immediate")!=null)
		 {
			 immediate = Boolean.parseBoolean(getParameter("immediate"));
		 }
		 
			if (getParameter("BUFFER_SIZE")!=null)
			{
				mpersistor.setBufferSize( Integer.parseInt(getParameter("BUFFER_SIZE")));
			}
		 
	}


	 



}
